package com.eascs.workflow.sequence.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.sequence.dao.SequenceDao;
import com.eascs.workflow.sequence.service.SequenceServer;

@Service
public class SequenceServerImpl implements SequenceServer {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SequenceDao sequenceDao;

	@Override
	public String getSeq(String type, int len, String prefix) {
		String sequenceStr;
		int curSeq = 0;
		try {
			if (StringUtils.isBlank(type) || type == null) {
				logger.info("SequenceServerImpl.getSeq error:{序列号类型}参数不能为空");
				return null;
			}
			if (prefix == null) {
				prefix = SequenceEntity.DEFALUT_PREFIX;
			}
			int count=0;
			int result=0;
			boolean flag=false;
			SequenceEntity seq =null;
			do{
				seq = sequenceDao.querySequences(type, prefix);
				if (seq != null) {
					if (len < (seq.getSequence() + "").length()) {
						logger.info("SequenceServerImpl.getSeq error:传入的序列号长度不能小于实际返回序列号长度[" + curSeq + "]，param{type:" + type + ",len:" + len + ",prefix:" + prefix + "}");
						return null;
					}
					result = sequenceDao.udpate(seq);
					if(result > 0){
						curSeq = seq.getSequence()+1;
					}
				} else {
					curSeq = SequenceEntity.SEQ_INDEX;
					SequenceEntity sequenceEntity = new SequenceEntity();
					sequenceEntity.setSeqType(type);
					sequenceEntity.setSeqPrefix(prefix);
					sequenceEntity.setSequence(curSeq);
					result = sequenceDao.insert(sequenceEntity);
				}
				sequenceStr = prefix + "-" + String.format("%0" + len + "d", curSeq);
				if(result <= 0){
					flag = true;
					if(count != 0 ){
						logger.info("SequenceServerImpl.getSeq 生成seqCode失败!  重试次数count:"+count+",flag:"+flag+"，Seq:"+sequenceStr);
					}
				}else{
					flag = false;
					logger.info("SequenceServerImpl.getSeq 生成seqCode成功!  重试次数count:"+count+",flag:"+flag+"，Seq:"+sequenceStr);
				}
				count++;
			} while ( count <= 3 && flag );
			if(result == 0){
				logger.info("SequenceServerImpl.getSeq error:修改或新增失败,重试次数达到上限!");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("SequenceServerImpl.getSeq error:" + e.getMessage());
			return null;
		}
		return sequenceStr;
	}

}
